// 用户管理模块
const { DatabaseManager } = require('./database')
const defaultUsers = require('./default_users.json')

class UserManager {
  constructor() {
    this.db = new DatabaseManager()
  }

  // 创建默认用户
  async createDefaultUsers() {
    console.log('👥 开始创建默认用户...')
    
    const createdUsers = []
    
    for (const userData of defaultUsers) {
      try {
        console.log(`📝 处理用户: ${userData.email}`)
        
        // 检查用户是否已存在
        const { data: existingUsers, error: listError } = await this.db.supabase.auth.admin.listUsers()
        
        if (listError) {
          console.error(`❌ 获取用户列表失败:`, listError)
          continue
        }
        
        let authUser = null
        const existingAuthUser = existingUsers.users.find(user => user.email === userData.email)
        
        if (existingAuthUser) {
          // 用户已存在，使用现有用户
          authUser = existingAuthUser
          console.log(`📝 用户 ${userData.email} 已存在，使用现有账户`)
        } else {
          // 创建新用户
          const { data: newAuthUser, error: authError } = await this.db.supabase.auth.admin.createUser({
            email: userData.email,
            password: userData.password,
            email_confirm: true,
            user_metadata: {
              name: userData.name,
              avatar_url: userData.avatar_url
            }
          })
          
          if (authError) {
            console.error(`❌ 创建用户 ${userData.email} 失败:`, authError)
            continue
          }
          
          authUser = newAuthUser.user
          console.log(`✅ 成功创建用户: ${userData.email}`)
        }
        
        // 检查用户资料是否已存在
        const { data: existingProfile, error: profileCheckError } = await this.db.supabase
          .from('user_profiles')
          .select('*')
          .eq('user_id', authUser.id)
          .single()
        
        let profile = null
        
        if (existingProfile && !profileCheckError) {
          // 用户资料已存在，更新信息
          const { data: updatedProfile, error: updateError } = await this.db.supabase
            .from('user_profiles')
            .update({
              name: userData.name,
              bio: userData.bio,
              avatar_url: userData.avatar_url,
              is_ai: userData.is_ai
            })
            .eq('user_id', authUser.id)
            .select()
            .single()
          
          if (updateError) {
            console.error(`❌ 更新用户资料 ${userData.name} 失败:`, updateError)
            continue
          }
          
          profile = updatedProfile
          console.log(`📝 更新用户资料: ${userData.name}`)
        } else {
          // 创建新用户资料
          const { data: newProfile, error: profileError } = await this.db.supabase
            .from('user_profiles')
            .insert({
              user_id: authUser.id,
              name: userData.name,
              bio: userData.bio,
              avatar_url: userData.avatar_url,
              is_ai: userData.is_ai
            })
            .select()
            .single()
          
          if (profileError) {
            console.error(`❌ 创建用户资料 ${userData.name} 失败:`, profileError)
            continue
          }
          
          profile = newProfile
          console.log(`✅ 成功创建用户资料: ${userData.name}`)
        }
        
        createdUsers.push({
          authId: authUser.id,
          profileId: profile.id,
          name: userData.name,
          isAi: userData.is_ai,
          email: userData.email
        })
        
        console.log(`✅ 用户准备就绪: ${userData.name} (${userData.is_ai ? 'AI' : '人类'})`)
        
      } catch (error) {
        console.error(`❌ 处理用户 ${userData.email} 时发生错误:`, error)
      }
    }
    
    console.log(`\n📊 用户处理完成: ${createdUsers.length}/${defaultUsers.length} 个用户`)
    return createdUsers
  }

  // 获取所有用户
  async getAllUsers() {
    try {
      const { data: users, error } = await this.db.supabase
        .from('user_profiles')
        .select('*')
        .order('name')
      
      if (error) {
        throw error
      }
      
      return { success: true, data: users }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 检查用户是否存在
  async checkUserExists(email) {
    try {
      const { data: existingUsers, error: listError } = await this.db.supabase.auth.admin.listUsers()
      
      if (listError) {
        throw listError
      }
      
      const user = existingUsers.users.find(user => user.email === email)
      return { exists: !!user, user }
    } catch (error) {
      return { exists: false, error: error.message }
    }
  }

  // 删除用户
  async deleteUser(userId) {
    try {
      // 删除用户资料
      const { error: profileError } = await this.db.supabase
        .from('user_profiles')
        .delete()
        .eq('user_id', userId)
      
      if (profileError) {
        throw profileError
      }
      
      // 删除认证用户
      const { error: authError } = await this.db.supabase.auth.admin.deleteUser(userId)
      
      if (authError) {
        throw authError
      }
      
      return { success: true, message: '用户删除成功' }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }

  // 清空所有用户
  async clearAllUsers() {
    console.log('🗑️  开始清空所有用户...')
    
    try {
      // 获取所有用户
      const { data: users, error } = await this.db.supabase
        .from('user_profiles')
        .select('user_id')
      
      if (error) {
        throw error
      }
      
      let deletedCount = 0
      
      for (const user of users) {
        try {
          const result = await this.deleteUser(user.user_id)
          if (result.success) {
            deletedCount++
            console.log(`✅ 删除用户: ${user.user_id}`)
          }
        } catch (error) {
          console.error(`❌ 删除用户 ${user.user_id} 失败:`, error)
        }
      }
      
      console.log(`📊 用户清空完成: ${deletedCount}/${users.length} 个用户`)
      return { success: true, deletedCount }
    } catch (error) {
      console.error('❌ 清空用户时发生错误:', error)
      return { success: false, error: error.message }
    }
  }

  // 获取用户统计信息
  async getUserStats() {
    try {
      const { data: users, error } = await this.db.supabase
        .from('user_profiles')
        .select('is_ai')
      
      if (error) {
        throw error
      }
      
      const total = users.length
      const aiUsers = users.filter(user => user.is_ai).length
      const humanUsers = total - aiUsers
      
      return {
        success: true,
        stats: {
          total,
          aiUsers,
          humanUsers,
          aiPercentage: total > 0 ? Math.round((aiUsers / total) * 100) : 0
        }
      }
    } catch (error) {
      return { success: false, error: error.message }
    }
  }
}

module.exports = UserManager
